﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Toolkit.Web.Mvc.ExtensionMethods;

namespace Toolkit.Web.Mvc.FilterAttributes
{
    public class TransferInvalidModelStateInTempDataAttribute : ActionFilterAttribute
    {
        public const string TempDataKey = "Toolkit.Web.Mvc.FilterAttributes.TransferInvalidModelStateInTempDataAttribute.Key";

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            // Only try to retrieve model state from temp data if result is a view result (not a redirect result).
            if (filterContext.Result is ViewResult)
            {
                // Try to get model state from temp data.
                ModelStateDictionary modelState = null;
                if (filterContext.Controller.TempData.ContainsKey(TempDataKey))
                {
                    modelState = filterContext.Controller.TempData[TempDataKey] as ModelStateDictionary;
                }

                if (modelState != null && !modelState.IsValid)
                {
                    // Merge in model state from temp data.
                    // Note: This will NOT and should NOT override any existing model state values from the current controller view state.
                    filterContext.Controller.ViewData.ModelState.Merge(modelState, false);
                }
            }
            // Only pass model state if it is not valid and user is being redirected.
            else if (((filterContext.Result is RedirectResult) || (filterContext.Result is RedirectToRouteResult)) && !filterContext.Controller.ViewData.ModelState.IsValid)
            {
                filterContext.Controller.TempData[TempDataKey] = filterContext.Controller.ViewData.ModelState;
            }

            base.OnActionExecuted(filterContext);
        }
    }
}
